#include "order/ordermanager.h"
#include "account.h"

Account* Account::s_inst = 0;

Account::Account()
: m_originBalance(10000)
{
    clearHistBalance();
}

Account* Account::inst()
{
    if (s_inst == 0) {
        s_inst = new Account();
    }
    return s_inst;
}

void Account::setBalance(int orderNo, double balance)
{
    m_balance = balance;
    int size = m_vecHistBalance.size() + 1;
    HistBalance histBalance;
    histBalance.m_id = size;
    histBalance.m_orderNo = orderNo;
    histBalance.m_balance = balance;
    m_vecHistBalance.push_back(histBalance);
    if (balance > m_maxBalance) {
        m_maxBalance = balance;
    }
    if (balance < m_minBalance) {
        m_minBalance = balance;
    }
    accountChanged();
}

double Account::getAccountFloating()
{
    OrderManager *orderManager = OrderManager::inst();
    return orderManager->getOrdersFloating();
}

double Account::getAccountEquity()
{
    return m_balance + getAccountFloating();
}

double Account::getAccountBalance()
{
    return m_balance;
}

double Account::getAccountFee()
{
    return m_fee;
}

void Account::clearHistBalance()
{
    m_vecHistBalance.clear();
    HistBalance histBalance;
    histBalance.m_id = 0;
    histBalance.m_orderNo = 0;
    histBalance.m_balance = m_originBalance;
    m_vecHistBalance.push_back(histBalance);
    m_balance = m_originBalance;
    m_maxBalance = m_balance;
    m_minBalance = m_balance;
    m_fee = 0;
}

void Account::addListener(AccountListener *listener)
{
    m_vecListener.push_back(listener);
}

void Account::accountChanged()
{
    for (int i = 0; i < m_vecListener.size(); ++i) {
        m_vecListener[i]->onAccountChanged();
    }
}